package cn.zc.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 *
 */
@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @RequestMapping
    public Result save(@RequestBody DishDTO dishDTO){
        dishService.save(dishDTO);
        //清除缓存
        String key ="dish_"+dishDTO.getCategoryId();
        redisTemplate.delete(key);
        return Result.success();
    }

    /**
     * 菜品分页查询
     * @param pageQueryDTO
     * @return
     */
    @GetMapping("/page")
    public Result page(DishPageQueryDTO pageQueryDTO){
        PageResult pageResult = dishService.page(pageQueryDTO);
        return Result.success(pageResult);
    }
    //批量删除菜品
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids){
        //清除缓存
        for (Long id : ids) {
            //根据id查询菜品分类category_id
            String key ="dish_"+dishService.getDishById(id).getCategoryId();
            redisTemplate.delete(key);
        }
        dishService.deleteBath(ids);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result getDishById(@PathVariable Long id){
        DishVO dishVO = dishService.getDishById(id);
        return Result.success(dishVO);
    }
    @PutMapping
    public Result update(@RequestBody DishVO dishVO){
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return dishService.update(dishVO);
    }
    @PostMapping("/status/{status}")
    public Result updateStatus(@RequestParam Long id, @PathVariable Integer status){
        dishService.updateStatus(id,status);
        return Result.success();
    }
    @GetMapping("/list")
    public Result list(Long categoryId){
        List<Dish> dishVOList = dishService.list(categoryId);
        return Result.success(dishVOList);
    }
}